#!/usr/bin/python

import sys
import matplotlib.pyplot as plt
import pylab
from matplotlib.backends.backend_pdf import PdfPages

filename = sys.argv[1]
f = open(filename, "rU")
fl = f.readlines()
outfile = sys.argv[2]

x1 = []
x2 = []
y1 = []
y2 = []

line = fl[4]
l = line.split('\t')
genome_size = int(l[7])

genome_coords = {}

for i in range(1, genome_size+1):
    genome_coords[i] = 0

for i, line in enumerate(fl[4:]):
    l = line.split('\t')
    start = int(l[0])
    stop = int(l[1])
    gs = int(l[7])
    identity = float(l[6])
    x1.append(start)
    x2.append(stop)
    y1.append(identity)
    y2.append(identity)
    for a in range(start, stop):
        genome_coords[a] = genome_coords[a] + 1

cov = []

for k, v in genome_coords.iteritems():
    cov.append(v)

#cov = []
#k = 1
#while k <= genome_size:
#    count = 0
#    for i, j in enumerate(x1):
#        if x1[i] < k < x2[i]:
#            count += 1
#    cov.append(count)
#    k += 1

#for x in range(1,genome_size+1):
#    count = 0
#    for i, j in enumerate(x1):
#        if x1[i] < x < x2[i]:
#            count += 1
#    cov.append(count)

gx = [1,genome_size]
gy = [10,10]

a = [x1, x2]
b = [y1, y2]

xcoords = range(1, genome_size+1)
print "xcoords: ", len(xcoords)
print "cov: ", len(cov)

fig = plt.figure(1, figsize=(14,8))

plt.subplots_adjust(wspace=2.0)

plt.subplot(211)
plt.plot(gx, gy, color='blue', marker='|', markersize=8.0,
    markeredgecolor='black', linestyle='-', linewidth=2.0)
plt.plot(a, b, color='orange', linestyle='-')
plt.axis([0, genome_size, 0, 110])
plt.title('Recruited cDNA reads')
plt.ylabel('% Identities')
plt.grid(True)

plt.subplot(212)
plt.plot(xcoords, cov, color='green', linestyle='-')
plt.axis([0, genome_size, 0, max(cov)+2])
plt.title('Coverage')
plt.xlabel('Genome coordinates(bp)')
plt.ylabel('Counts')
plt.grid(True)

#plt.show()
#pp = PdfPages(outfile, format='pdf')
plt.savefig(outfile, format='pdf')
